<?php

	// +----------------------------------------------------------------------
	// | 邮件发送渠道插件
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace addon\email;

	use PHPMailer\PHPMailer\PHPMailer;
	use think\Event;
	use think\Exception;
	use yicmf\addon\controller\Controller;
	use app\model\ucenter\EmailHistory as EmailHistoryModel;

	class Email extends Controller
	{

		protected $config_builder = [
			'keyList' => [
				[
					'field' => 'open',
					'title' => '开启邮件发送',
					'type' => 'radio',
					'size' => '30',
					'options' => [0 => '否', 1 => '是'],
					'default' => 1
				], [
					'field' => 'channel',
					'title' => '发送渠道',
					'type' => 'radio',
					'size' => '30',
					'tips' => '',
					'options' => ['PHPMailer' => '自定义邮箱', 'aliyun' => '阿里云邮箱', 'sendcloud' => 'sendcloud'],
					'default' => 1
				],
				[
					'field' => 'host',
					'title' => 'HOST',
					'type' => 'string',
					'size' => '30',
					'default' => ''
				],
				[
					'field' => 'username',
					'title' => '用户名',
					'type' => 'string',
					'size' => '50',
					'default' => ''
				],
				[
					'field' => 'password',
					'title' => '用户密码',
					'type' => 'string',
					'size' => '30',
					'default' => ''
				],
				[
					'field' => 'set_from_address',
					'title' => '来源邮件地址',
					'type' => 'string',
					'size' => '30',
					'default' => ''
				],
				//                [
				//                    'field' => 'set_reply_address',
				//                    'title' => '回复邮件地址',
				//                    'type' => 'string',
				//                    'size' => '30',
				//                    'default' => ''
				//                ],
				[
					'field' => 'set_from_name',
					'title' => '来源邮件名称',
					'type' => 'string',
					'size' => '30',
					'default' => '客服中心'
				],

				[
					'field' => 'set_reply_address',
					'title' => '回复邮件地址',
					'type' => 'string',
					'size' => '30',
					'default' => ''
				],
				[
					'field' => 'set_reply_name',
					'title' => '回复名称',
					'type' => 'string',
					'size' => '30',
					'default' => '客服中心'
				],
				[
					'field' => 'free_num',
					'title' => '免费条数',
					'type' => 'hidden',
					'default' => 200
				]
			],
			'explaints' => [
				'25端口多数已经被封，默认采用465，如果依旧不行，建议使用
<a href="https://www.aliyun.com/1111/new?userCode=r74z8vqb" target="_blank">阿里云邮件推送</a> 、
<a href="https://curl.qcloud.com/fVXjnTEG" target="_blank">腾讯邮件推送</a> 、
 <a href="https://sendcloud.sohu.com/v3/#/register" target="_blank">sendcloud</a> 发送',
				'如果有疑问，请联系我们',
			]
		];


		/**
		 * 发送模版邮件
		 * $param = [];
		 * $param['address'] = 'lilwil@163.com';
		 * $param['template_name'] = 'base';
		 * $param['subject'] = '标题部分';
		 * $param['body'] = '内容';
		 * $data = Event::trigger('send_email',$param, true);
		 * @param $param
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/15 8:47
		 */
		public function sendEmail($param)
		{
			try {
				if (1 != $this->getConfig('open')) {
					throw new Exception('没有开启发送邮件功能');
				}

				$config = $this->getConfigBest();
				if ('smtp.sendcloud.net' == $config['host']) {
					$data = $this->_send_cloud($param, $config);
				} else {
					if (!extension_loaded('openssl')) {
						throw new Exception('请开启 php_openssl 扩展！');
					}
					$mailer = new PHPMailer();
					$mailer->isSMTP();
					$mailer->setLanguage('ch');
					$mailer->SMTPDebug = 0; // smtp
					$mailer->Host = $config['host']; // smtp
					$mailer->Port = 465;
					$mailer->CharSet = 'utf-8';
					$mailer->SMTPAuth = true;
					$mailer->SMTPSecure = 'ssl';
					$mailer->Username = $config['username']; // 登录名
					$mailer->Password = $config['password'];
					$mailer->setFrom($config['set_from_address'], $config['set_from_name']); // 设置发件人的邮箱及其名称
					$mailer->addReplyTo($config['set_reply_address'], $config['set_reply_name']); // 设置回复的邮箱及其名称
					//                    $mailer->addReplyTo($config['set_reply_address'], $config['set_reply_name']); // 设置回复的邮箱及其名称
					$mailer->isHTML();
					$mailer->Subject = '=?utf-8?B?' . base64_encode($param['subject']) . '?=';
					// $mailer->AltBody = $value;
					// $mailer->addAttachment($file);
					$mailer->Body = $param['body'];
					// if (!empty($mailer->signature)) {
					// $param['body'] .= htmlspecialchars_decode($mailer->signature);
					// }
					$mailer->addAddress($param['address']);
					$data['channel'] = $config['channel'];
//					$re = $mailer->send();
					if (true === $mailer->send()) {
						$data['data'] = '发送成功';
						$data['message'] = '发送成功';
						$data['code'] = 0;
					} else {
						$data['data'] = $mailer->ErrorInfo;
						$data['message'] = $mailer->ErrorInfo;
						$data['code'] = 1;
					}
				}
			} catch (\Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		protected function _send_cloud($param, $config)
		{
			$param = [
				'apiUser' => $config['username'],
				'apiKey' => $config['password'],
				'from' => $config['set_from_address'],
				'fromName' => $config['set_from_name'],
				'to' => $param['address'],
				'subject' => $param['subject'],
				'html' => $param['body'],
				'respEmailId' => 'true'
			];
			$options = [
				'http' => [
					'method' => 'POST',
					'header' => 'Content-Type: application/x-www-form-urlencoded',
					'content' => http_build_query($param)
				]];
			$context = stream_context_create($options);
			$result = json_decode(file_get_contents('http://api.sendcloud.net/apiv2/mail/send', FILE_TEXT, $context), true);
			$data['channel'] = $config['channel'];
			if (true == $result['result']) {
				$data['code'] = 0;
				$data['message'] = '发送成功';
				$data['data'] = $result['info']['emailIdList'];
			} else {
				$data['code'] = 1;
				$data['message'] = $result['message'];
				$data['data'] = $result['message'];
			}
			return $data;
		}
		/**
		 * 获取最佳邮箱
		 * @return array|mixed|string[]|null
		 * @author 微尘 <yicmf@qq.com>
		 */
		protected function getConfigBest()
		{
//			$count = EmailHistoryModel::whereTime('create_time', 'today')->count();
			return $this->getConfig();
		}
		public function subscribe(Event $event)
		{
			$event->listen('send_email', [$this,'sendEmail']);
		}
		public function install(){}

		public function uninstall(){}

	}
